<!-- @format -->

<template>
  <UseSpace title="尝试手写 Form 组件">
    <Form @submit="onSubmit" :initial-values="theInitialValues">
      <FieldArray
        ref="theFieldArrayRef"
        name="links"
        v-slot="{ fields, push, remove }"
      >
        <div v-for="(entry, idx) in fields" :key="entry.key">
          {{ `links[${idx}]` + `--` + entry.value?.type }}
          <template v-for="(item, index) in theComponentsTypeArr" :key="index">
            <Field :name="`links[${idx}]`" v-if="entry.value?.type == item">
              <component
                ref="componentRef"
                :is="onImportComponentName(item)"
                :data="entry.value"
                @change="onCompChange"
              ></component>
            </Field>
          </template>
          <button type="button" @click="remove(idx)">Remove</button>
        </div>
        <button type="button" @click="push({ type: 'Input' })">Add</button>
      </FieldArray>
      <button>Submit</button>
    </Form>
  </UseSpace>
</template>
<script lang="ts" setup>
  import { onMounted, ref, markRaw, defineAsyncComponent } from 'vue'
  import { Field, Form, FieldArray } from 'vee-validate'
  import { theComponentsTypeArr } from './conf'
  import Select from './components/Select/Index.vue'
  import { theInitialValues } from './mock-data'
  import { FormProSchemaBox, FormProSchema } from './types'

  const theCurrentCopmonentName = ref()
  theCurrentCopmonentName.value = markRaw(Select)

  const theFieldArrayRef = ref()

  const onImportComponentName = (name: string) => {
    return markRaw(
      defineAsyncComponent(() => import(`./components/${name}/Index.vue`)),
    )
  }

  const onCompChange = (
    currentCompValue: any,
    currentCompData: FormProSchema,
  ) => {
    theFieldArrayRef.value!.update(0, {
      ...currentCompData,
      value: currentCompValue,
    })

    console.log('cu ===>', currentCompValue, currentCompData)
    // theInitialValues.value.links.forEach((item: FormProSchema) => {
    //   if (item.field === currentCompData.field) {
    //     item.value = currentCompValue
    //   }
    // })
    // console.log(
    //   'theInitialValues.value.links ===>',
    //   theInitialValues.value.links,
    // )
  }

  function onSubmit(values: any) {
    console.log('values ===>', JSON.parse(JSON.stringify(values.links)))

    // alert(JSON.stringify(, null, 2))
  }
  onMounted(() => {})
</script>
